<template>
<div>
<headerSearch :title="IMtitle"></headerSearch>

  <div class="content" id="content" style="padding:0.2rem;">
 <!--   <div>
      <div class="others">
          <img  class="chat-avatar" src="../common/images/userAvatar.png">
          <span></span>
          <span class="chat-left-span">您好，我对你这个产品感兴趣，可以详细了解吗？</span>
          <img class="chat-image"/>
      </div>
      <div style="text-align: right;marin-top:10px;">
          <img class="chat-image"/>
          <span style="background-color: #e50838" ></span>
          <span class="chat-right-span" >你好</span>
          <img  class="chat-avatar"  src="../common/images/userAvatar.png"/>
      </div>

    </div>
 -->

    <div v-for="(msg, m) in currentChat.msgList" :key="m">
            <div v-if="parseInt(msg.from_id) !== parseInt(info.im_user)" class="others">
                <img :src="msg.avatar" class="chat-avatar">
                <small>
                  <span class="triangle"></span>
                  <span class="chat-left-span">{{msg.msg}}</span>
                </small>
                <img :src="msg.msg" v-if="parseInt(msg.msg_type) === 1" class="chat-image"/>
            </div>
            <div style="text-align: right;marin-top:10px;" v-if="parseInt(msg.from_id) === parseInt(info.im_user)">
                <img :src="msg.msg" v-if="parseInt(msg.msg_type) === 1" class="chat-image"/>
                <small>
                  <span class="right_triangle"></span>
                  <span class="chat-right-span">{{msg.msg}}</span>
                </small>
                <img :src="info.userhead" class="chat-avatar"/>
            </div>
          </div>
  </div>


  <div class="chat">
    <input type="text"  v-model="msg">
    <button class="SendMsg" @click="handleSendMsg(2)">发送</button>
    <!-- <i class="iconfont icon-icon02"  @click="handleSendMsg(2)"></i> -->
  </div>

</div>
  
</template>

<script>
import {
    ws, deleteChat, createChat, updateChat, friendList, deleteFriend, messageList, imageUrl
  } from '../api/api';
import {getNowFormatDate, validateURL} from '../utils/tool';
import headerSearch from '../public/header-search.vue';
  export default {
    name: 'Chat',
    data() {
      return {
        msg: '',  // 聊天输入框
        info: {
        }, // 个人信息
        currentChat: {  // 当前聊天对象
          },
        avatar:'',
        socket: '',
        IMtitle:'',
        friendList: [], // 好友列表
        chatList: [],  // 聊天列表
        userList: [],  // 用户列表
        groupUserList: [],
        sendList: new Map(), // 存储所有已发消息
        currentFriend: { // 当前好友
          id: '',
          username: '',
          avatar: '',
          age: '',
          sex: ''
        },
        visible: {
          repeatConnect: false,
          edit: false,
          addFriend: false,
          chatList: true,
          friendList: false,
          newFriend: false,
          applyList: false,
          createGroup: false,
          reConnect: true,
          groupUser: false,
          loadingMessage: false
        },
        socket: '',
        isConnect: false,
        haveNotReadApply: false,
        getMsgFlag: true,
        fileList: [],
        type:'',
        newType:0,
      }
    },
    components: {headerSearch},
     computed: {
      // // 获取头像
      // avatar () {
      //   return this.$store.state.info.avatar;
      // },
     },
    updated () {
      // 消息框滚动条处理
      let toBottom
      if (!this.currentChat.scrollBottom) {
        toBottom = 0;
      } else {
        toBottom = this.currentChat.scrollBottom;
      }
      let content = document.getElementById('content');
      content.scrollTop = content.scrollHeight - toBottom;
    },
    methods: {
      
      // 判断消息是否为url
      isLink (msg) {
        return validateURL(msg);
      },
      // 消息内容url化
      linkMsg (msg) {
        return `<a href="${msg}" target="_blank">${msg}</a>`
      },
      // 切换当前聊天对象
      changeChat (chat) {
        this.currentChat = chat;
        // 消息设置为已读
        if (chat.notReadNum > 0) {
          updateChat({id: chat.chat_id}).then(res => {
            if (parseInt(res.status) === 1) {
              chat.notReadNum = 0;
            }
          })
        }
      },
      // scroll触发函数，记录每个聊天框滚动条的滚动位置
      handleScroll () {
        let doc = document.getElementById('content')
        this.currentChat.scrollBottom = doc.scrollHeight - doc.scrollTop;
        if (doc.scrollTop < 10) {
          this.fetchMessageList(this.currentChat);
        }
      },
      //  获取聊天记录
      fetchMessageList (chat) {
        if (chat.noMsg !== true && this.getMsgFlag === true) {
          this.visible.loadingMessage = true;
          this.getMsgFlag = false;
          chat.page += 1;
          let params = {
            page: chat.page,
            id: chat.chat_id,
            time: chat.getMsgTime
          }
          messageList(params).then(res => {
            this.visible.loadingMessage = false;
            if (parseInt(res.status) === 1) {
              if (res.msgList.length === 0) {
                this.$set(chat, 'noMsg', true);
              } else {
                chat.msgList = res.msgList.concat(chat.msgList);
              }
            }
            this.getMsgFlag = true;
          })
        }
      },
      // 注销登陆
      handleLoginOut () {
        this.socket.close();
        localStorage.setItem('token', '');
        this.$router.push('/');
      },
      // 朋友详情栏点击`发送消息`触发事件
      handleChat (friendId) {
        let access_token = window.localStorage.getItem('access_token');
        let chat = this.chatList.find(e => parseInt(e.id) === parseInt(friendId));
 
        if (chat) {
          this.switchInterface('chat');  // 切换到聊天界面
          this.changeChat(chat);   // 将当前聊天对象切换成该聊天
        } else {
          createChat({targetId: friendId, access_token: access_token}).then(res => {
            console.log(res);
            // if (parseInt(res.status) === 1) {
              
            //   chat = res.chat;
            //   this.chatList.unshift(chat);
            //   this.switchInterface('chat');  // 切换到聊天界面
            //   this.changeChat(chat);    // 将当前聊天对象切换成该聊天
            // }
            if(res.code == 200) {
              chat = res.chat;
              this.chatList.unshift(chat);
              this.switchInterface('chat');  // 切换到聊天界面
              this.changeChat(chat);    // 将当前聊天对象切换成该聊天
            }
          })
        }
      },
      // 切换界面
      switchInterface (type) {
        if (type === 'friend') {
          this.visible.friendList = true;
          this.visible.chatList = false;
        }
        if (type === 'chat') {
          this.visible.friendList = false;
          this.visible.chatList = true;
        }
      },
      // webSocket发送消息
      send (msg) {
        console.log('信息',this.socket.readyState);
        console.log('信息2',WebSocket.OPEN);
        return new Promise((resolve, reject) => {
          if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(msg))
            resolve()
          } else {
            this.isConnect = false;
            reject(new Error())
          }
        })
      },

      // 发送聊天消息
      handleSendMsg (t) {
        console.log('发送消息',t);
        if(t == 1){//新的好友第一次发送信息
          if(this.newType == 0){
              let msg = {
              chat_id: this.currentChat.chat_id,
              msg: '我通过了你的朋友验证请求，现在我们可以开始聊天了',
              type: 'msg',
              msg_type: 0,
              from_id: this.info.im_user,
              to_id: this.currentChat.target_id,
              is_read: 1,
              avatar: this.info.userhead
              }
              console.log('333',msg);
              this.send(msg).then(() => {
                // this.sendList.set()
                this.currentChat.msgList.push(msg);
                this.currentChat.last_chat_time = getNowFormatDate();
                this.msg = '';
                if (this.currentChat.notReadNum > 0) {
                  updateChat({id: this.currentChat.chat_id}).then(res => {
                    if (parseInt(res.status) === 1) {
                      this.currentChat.notReadNum = 0;
                    }
                  })
                }
              })
          }
          
        }else{
          // if (this.msg === '') {
          //   this.$message.error('不能发送空消息!');
          //   return false;
          // }
         if(this.msg == ''){
           this.$openTips({
              text: '不能发送空白消息',
              time: 1000
            })
            return false;
         }
          let msg = {
            chat_id: this.currentChat.chat_id,
            msg: this.msg,
            type: 'msg',
            msg_type: 0,
            from_id: this.info.im_user,
            to_id: this.currentChat.target_id,
            is_read: 1,
            avatar: this.info.userhead
          }
          console.log('888',msg);
          this.send(msg).then(() => {
            // this.sendList.set()
            this.currentChat.msgList.push(msg);
            this.currentChat.last_chat_time = getNowFormatDate();
            this.msg = '';
            if (this.currentChat.notReadNum > 0) {
              updateChat({id: this.currentChat.chat_id}).then(res => {
                if (parseInt(res.status) === 1) {
                  this.currentChat.notReadNum = 0;
                }
              })
            }
          })
        }

        // console.log('1919',msg);
        // this.send(msg).then(() => {
        //   // this.sendList.set()
        //   this.currentChat.msgList.push(msg);
        //   this.currentChat.last_chat_time = getNowFormatDate();
        //   this.msg = '';
        //   if (this.currentChat.notReadNum > 0) {
        //     updateChat({id: this.currentChat.chat_id}).then(res => {
        //       if (parseInt(res.status) === 1) {
        //         this.currentChat.notReadNum = 0;
        //       }
        //     })
        //   }
        // })
      },
      
      // 开启ws链接
      openConnect () {
        let token = window.localStorage.getItem('access_token');
       // let token = 'ab5ac4826d5ccb041b9cbc17714f3dfc';
        this.socket = new WebSocket(`${ws}?token=${token}`);
        this.socket.onopen = this.onConnect;
        this.socket.onmessage = this.onMessage;
        this.socket.onclose = this.onClose;
        this.socket.onerror = this.onError;
     
      },
      onError () {
        this.$confirm('聊天服务器连接失败', '提示', {
          confirmButtonText: '重新连接',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.openConnect();
        }).catch(() => {
          localStorage.setItem('token', '');
          this.$router.push('/');
        })
      },
      // 链接成功事件
      onConnect (ws) {
        // this.$message.success(`已成功连接到聊天服务器`);
        this.isConnect = true;
        if(this.type == 'new'){//新添加的好友发送礼貌问候语
            this.handleSendMsg(1);
            this.newType = 1;
        }
        console.log('链接状态',this.socket.readyState);
      },
      // 断开连接触发函数
      onClose () {
        this.isConnect = false;
      },
      // 聊天消息接受处理函数
      handleMsg (data) {
        if ('chat' in data) {
          console.log(1515);
          const chat = data.chat;
                    console.log('头像', data)
          chat.notReadNum += 1;
          chat.msgList.push(data.msg);
          this.chatList.unshift(chat);
        } else {
          console.log('999',data.msg);
          let chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.msg.chat_id));
          chat.msgList.push(data.msg);
          this.currentChat.msgList.push(data.msg);
          chat.last_chat_time = data.msg.time;
          chat.notReadNum += 1;
        }
      },
      // 接受消息事件
      onMessage (ws) {
        console.log('3322',ws);
        try {
            let data = JSON.parse(ws.data);
             switch (data.type) {
          case 'chatList': // 聊天列表
            this.chatList = data.chatList
            break
          case 'msg':
            this.handleMsg(data)
            break
          case 'forbidden':  // token不正确
            this.handleLoginOut()
            break
          case 'repeat':  // 被踢
            this.visible.reConnect = false
            this.socket.close()
            localStorage.setItem('token', '')
            this.$alert('你的账号已在别处登陆', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$router.push('/')
              }
            })
            break
          case 'newApply':   // 有新的好友申请
            this.haveNotReadApply = true
            break
          case 'applySucc':  // 好友申请被同意
            this.handleFriendList()
            this.$message.success('"' + data.friend.username + '"已经同意你的好友申请')
            break
          case 'newGroup': // 接受新群组
            this.chatList.unshift(data.group)
            break
          case 'repeatConnect': // 重复连接
            this.socket.close()
            this.visible.repeatConnect = true
            this.visible.reConnect = false
            break
          case 'goOnline':  // 上线消息
            let chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = true
            break
          case 'goOffLine':  // 下线消息
            chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = false
            break
          case 'quitGroup':   // 退出群组消息
            const chatId = data.chatId
            const userId = data.userId
            chat = this.chatList.find((element) => parseInt(element.chat_id) === parseInt(chatId))
            const index = chat.userList.findIndex(element => parseInt(element.id) === parseInt(userId))
            const user = chat.userList.splice(index, 1)
            this.$message.success(`<${user.username}>退出了群组<${chat.group_name}>`)
            break
        }
        } catch (err) {
            console.log(JSON.stringify(err));
        }

       
      },
      
    },
    mounted () {
      let that = this;
      that.type = this.$route.query.type;
      that.currentChat = this.$route.query.chat;
      that.IMtitle = that.currentChat.username ? that.currentChat.username : that.currentChat.group_name;
      that.info = JSON.parse(window.localStorage.getItem('userInfo'));
      console.log('当前聊天对象',that.currentChat);
      this.openConnect();
      
      console.log('nnn',that.IMtitle);
      
      
       
     
        this.$store.commit('setPage', 2);//设置需要预请求的参数
    },
    watch: {
      isConnect: function (newResult, oldResult) {
        if (newResult === false && this.$route.path === '/chat' && this.visible.reConnect === true) {
          this.$confirm('聊天服务器已断开', '提示', {
            confirmButtonText: '重新连接',
            cancelButtonText: '取消',
            type: 'error'
          }).then(() => {
            this.openConnect();
          }).catch(() => {
            localStorage.setItem('token', '');
            this.$router.push('/');
          })
        }
      }
    },
  }

</script>
<style>
.others{
  margin: 0.28rem 0;
  text-align:left;
}
.chat-avatar{
  width:0.8rem;
  height:0.8rem;
  border-radius: 50%;
}
small {
  position: relative;
}
small .triangle {
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-right: 8px solid #f2f2f2;
    position: absolute;
    left: -0.16rem;
    top: 0.2rem;
}
small .right_triangle {
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-left: 8px solid #e50838;
    position: absolute;
    right: -0.16rem;
    top: 0.2rem;
}
.chat-right-span{
    background-color: #e50838;
    color: #fff;
    font-size: 0.28rem;
    display: inline-block;
    vertical-align: top;
    line-height: 0.48rem;
    max-width: 70%;
    min-height: 0.3rem;
    padding: 0.2rem;
    word-break: break-all;
    word-wrap: break-word;
    text-align: left;
    border-radius: 5px;
    margin-top: 0.2rem;
}
.chat-left-span{
    background-color:#f2f2f2;
    color: #333;
    font-size: 0.28rem;
    display: inline-block;
    vertical-align: top;
    line-height: 0.48rem;
    max-width: 70%;
    min-height: 0.3rem;
    padding: 0.2rem;
    word-break: break-all;
    word-wrap: break-word;
    text-align: left;
    border-radius: 5px;
    margin-top: 0.2rem;
}
.chat {
  position: absolute;
  bottom: 0;
  left: 0;
}
.chat .SendMsg {
    background-color: #e50838;
    line-height: 0.6rem;
    height: 0.6rem;
    padding: 0 0.14rem;
    border-radius: 4px;
    margin: auto;
    color: #fff;
    margin-right: -0.04rem;
}

</style>
